import React, { Component } from 'react'

export default class Fome extends Component {
    constructor() {
        super();
        this.state = {
            val1: '12k',
            val2: '2',
            val3: ['rap']
        }
    }
    // 双向绑定
    getVal1(e) {
        // console.log(e.target.value);
        this.setState({
            val1: e.target.value
        }, () => {
            console.log(this.state.val1);
            console.log(e.target.value);
        })
    }
    // 处理单选
    changeVal2(e) {
        // console.log(e.target.value);
        this.setState({
            val2: e.target.value
        })
    }
    // 处理多选
    changeVal3(e) {
        // console.log(e.target.value);
        let arr = [...this.state.val3];
        // 如果已经存在，就删除；不存在就添加
        if(arr.includes(e.target.value)) {
            // 删除
            arr.splice(arr.indexOf(e.target.value), 1)
        }else {
            // 添加
            arr.push(e.target.value);
        }
        this.setState({
            val3: arr
        })
    }
    render() {
        return (
            <>
                <p>React对于表单元素的处理</p>
                {/* value是数据控制视图，数据变化时，输入框的value更新，页面也更新 */}
                {/* onChange 是页面控制数据，当输入框change时，就会通过setState修改数据 */}
                <input value={this.state.val1} onChange={(e) => this.getVal1(e)} />
                <p>{this.state.val1}</p>
                <br />  
                <label>性别</label>
                <input type="radio" value="1" name='sex' onChange={(e)=>this.changeVal2(e)} checked={this.state.val2 === '1'} />男
                <input type="radio" value="2" name='sex' onChange={(e)=>this.changeVal2(e)} checked={this.state.val2 === '2'} />女
                <input type="radio" value="3" name='sex' onChange={(e)=>this.changeVal2(e)} checked={this.state.val2 === '3'} />保密
                <p>您的选择是：{this.state.val2}</p>
                <label>爱好</label>
                <input type="checkbox" value="sing" name='hooby' onChange={(e)=>this.changeVal3(e)} checked={this.state.val3.includes('sing')} />唱
                <input type="checkbox" value="dance" name='hooby' onChange={(e)=>this.changeVal3(e)} checked={this.state.val3.includes('dance')} />跳
                <input type="checkbox" value="rap" name='hooby' onChange={(e)=>this.changeVal3(e)} checked={this.state.val3.includes('rap')} />rap
                <input type="checkbox" value="basketball" name='hooby' onChange={(e)=>this.changeVal3(e)} checked={this.state.val3.includes('basketball')} />打篮球
                <p>您的选择是：{this.state.val3}</p>
            </>
        )
    }
}
